<?php

namespace We7\V211;

defined('IN_IA') or exit('Access Denied');
/**
* [WeEngine System] Copyright (c) 2014 W7.CC
* Time: 1573456942
* @version 2.1.1
*/

class InitUsersOperateStar {

	/**
	 *  执行更新
	 */
	public function up() {
		function user_save_operate_star2($uid, $type, $uniacid, $module_name) {
			load()->model('module');
			if (!in_array($type, array(1, 2)) || empty($uniacid)) {
				return error(-1, '参数不合法！');
			}
			if (2 == $type) {
				if (!empty($module_name) && !module_exist_in_account($module_name, $uniacid)) {
					return error(-1, '平台账号无该模块权限，请更新缓存后重试！');
				}
			}
			$data = array('uid' => $uid, 'uniacid' => $uniacid, 'module_name' => $module_name, 'type' => $type);
			if (1 == $type) {
				unset($data['module_name']);
			}
			$if_exists = table('users_operate_star')->where($data)->get();
			if ($if_exists) {
				$result = table('users_operate_star')->where($data)->delete();
			} else {
				$data['createtime'] = TIMESTAMP;
				$maxrank = table('users_operate_star')->getMaxRank();
				$data['rank'] = intval($maxrank) + 1;
				$result = table('users_operate_star')->fill($data)->save();
			}
			if ($result) {
				return error(0, '');
			} else {
				return error(-1, '设置失败！');
			}
		}
		$shortcult_list = pdo_getall('core_menu_shortcut', array('position' => 'home_welcome_system_common'));
		if (!empty($shortcult_list)) {
			$account_info = pdo_getall('account', array('uniacid IN' => array_column($shortcult_list, 'uniacid')), array(),'uniacid');
			foreach ($shortcult_list as $info) {
				if (empty($info['uniacid'])) {
					continue;
				}
				if (empty($account_info[$info['uniacid']]) || 1 == $account_info[$info['uniacid']]['isdeleted']) {
					continue;
				}
				$uni_modules_table = table('uni_modules');
				$uni_modules_table->searchGroupbyModuleName();
				$own_account_modules_all = $uni_modules_table->getModulesByUid($info['uid']);
				if (!empty($info['modulename']) && !in_array($info['modulename'], array_column($own_account_modules_all['modules'], 'module_name'))) {
					continue;
				}
				if (!empty($info['modulename'])) {
					$data[] = array('module_name' => $info['modulename'], 'uniacid' => $info['uniacid'], 'uid' => $info['uid']);
				} else {
					$data[] = array('uniacid' => $info['uniacid'], 'uid' => $info['uid']);
				}
			}
			foreach ($data as $item) {
				if (!empty($item['module_name'])) {
					user_save_operate_star2($item['uid'], 2, $item['uniacid'], $item['module_name']);
				} else {
					user_save_operate_star2($item['uid'], 1, $item['uniacid'], '');
				}
			}
		}
	}

	/**
	 *  回滚更新
	 */
	public function down() {


	}
}
